# -*- coding: utf-8 -*-
import os

from multiprocessing import Process

from tornado.ioloop import IOLoop

from program_top.utilities.csv_and_json_serialisation import clean_load_json, temperarily_save_a_local_json
from program_top.utilities.environment_and_platform import get_current_environment_pack
from program_top.utilities.my_timer import schedule

def defaul_run(self):
	'''默认进程函数'''
	if hasattr(self, 'config_file'):
		self.__working_instance=self.__working_type(self.config_file)
	else:
		self.__working_instance=self.__working_type()
		pass
	IOLoop.current().start()
	pass


class my_engine(Process):
	'''
	进程引擎，接受socket监听作为事件循环，发出请求的时候发起连接
	初始化确定本进程的执行参数，包括平台，python版本
	'''
	
	def __set_schedules(self,schedule_config_dict):
		'''构造时只执行一次，加载时间表'''
		self.__schedules={}
		
		if schedule_config_dict.has_key('start'):
			self.__schedules["start"]=schedule(schedule_config_dict['start'], self.start)
		if schedule_config_dict.has_key('end'):
			self.__schedules["end"]=schedule(schedule_config_dict['end'], self.terminate)
		pass
	
	def __init__(self,working_type=None,config_file=None):
		super(my_engine, self).__init__()
		
		environment_pack=get_current_environment_pack()
		if working_type.__class__.__name__=='function':#加载函数模式
			function_name=working_type.__name__
			self.run=working_type
			function_config_filename=environment_pack['runtime_paths']['config_file_dir']+function_name+'.json'
			if not os.path.isfile(function_config_filename):
				temperarily_save_a_local_json({},function_config_filename)
			config_dict=clean_load_json(function_config_filename)
			
			if config_dict.has_key('schedule'):#如果有时间表则设定启动时间，否则直接启动
				self.__set_schedules(config_dict['schedule'])
			else:
				self.start()
				
		else:#加载类模式
			if config_file:
				self.config_file=config_file
			
			if working_type:#加载类模式
				self.__working_type=working_type
				self.__working_instance=None
			self.run=defaul_run
			self.start()
			pass
		pass

	def __self_register_from_hub(self):
		pass

	
	pass